using System;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using mojoPortal.Web;
using mojoPortal.Web.Framework;
using mojoPortal.Web.UI;
using Resources;
using eStore.Business;
using eStore.Helpers;
using System.Collections;
using mojoPortal.Business;
using ud_Utilities;
using System.Collections.Generic;

namespace eStore.UI
{
    public partial class AdminCategoryPage : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private Store store;
        private eStoreConfiguration config = new eStoreConfiguration();
        protected string EditContentImage = WebConfigSettings.EditContentImage;
        protected string DeleteLinkImage = WebConfigSettings.DeleteLinkImage;
        protected string DeleteLinkTooltip = eStoreResources.DeleteLinkTooltip;
        protected string DeleteLinkImageUrl = string.Empty;
        protected string EditLinkText = eStoreResources.EditEntryLink;
        protected string EditLinkTooltip = eStoreResources.EditEntryLink;
        protected string EditLinkImageUrl = string.Empty;
        readonly eStoreDB repository = new eStoreDB();

        protected void Page_Load(object sender, EventArgs e)
        {

            LoadSettings();

            if (!UserCanEditModule(moduleId))
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }

            SetupCss();
            PopulateLabels();
            PopulateControls();

        }

        private void PopulateControls()
        {
            if (store == null) { return; }

            if (!Page.IsPostBack)
            {
                PopulateRootCategories();
            }
        }

        private void PopulateRootCategories()
        {
            lbCategory.DataSource = repository.GeteStoreRootCategoriesByModuleID(moduleId);
            lbCategory.DataTextField = "Name";
            lbCategory.DataValueField = "CategoryID";
            lbCategory.DataBind();
            PopulateChildNode(lbCategory);
        }

        private void PopulateChildNode(ListBox root)
        {
            for (int i = 0; i < root.Items.Count; i++)
            {
                List<ud_eStoreCategory> children = repository.GeteStoreChildCategoryByCatID(int.Parse(root.Items[i].Value));
                if (children.Count <= 0) continue;
                string prefix = string.Empty;
                while (root.Items[i].Text.StartsWith("-"))
                {
                    prefix += root.Items[i].Text.Substring(0, 3);
                    root.Items[i].Text = root.Items[i].Text.Remove(0, 3);
                }
                root.Items[i].Text = prefix + root.Items[i].Text;
                foreach (ud_eStoreCategory child in children)
                {
                    ListItem list = new ListItem
                                        {
                                            Text = prefix + @"---" + child.Name,
                                            Value = child.CategoryID.ToString()
                                        };
                    root.Items.Insert(root.Items.IndexOf(root.Items[i]) + 1, list);
                }
            }
        }

        protected string BuildCategoryEditQueryString(string catID)
        {

            string result = "?pageid=" + pageId.ToString(CultureInfo.InvariantCulture)
                + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture)
                + "&catid=" + catID;
            return result;

        }

        private void PopulateLabels()
        {
            lnkStoreMenu.Text = eStoreResources.StoreManagerHeading;
            lnkStoreMenu.NavigateUrl = SiteRoot + "/eStore/AdminDashboard.aspx?pageid="
                                       + pageId.ToString(CultureInfo.InvariantCulture)
                                       + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            lnkCurrentPage.Text = eStoreResources.CategoryAdministrationLink;
            lnkCurrentPage.NavigateUrl = Request.Url.ToString();

            Title = SiteUtils.FormatPageTitle(siteSettings, eStoreResources.CategoryAdministrationLink);
            ltrTitle.Text = eStoreResources.CategoryAdministrationLink;
            btnAddNew.Text = eStoreResources.CategoryAddNewButton;
            btnAddNew.PostBackUrl = SiteRoot
                + "/eStore/AdminCategoryEdit.aspx?pageid=" + pageId.ToString(CultureInfo.InvariantCulture)
                + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            mojoBasePage basePage = Page as mojoBasePage;
            if (basePage != null)
            {
                if (!basePage.UseTextLinksForFeatureSettings)
                {
                    ibtnEdit.ImageUrl = ImageSiteRoot + "/Data/SiteImages/" + EditContentImage;
                    ibtnDelete.ImageUrl = ImageSiteRoot + "/Data/SiteImages/" + DeleteLinkImage;
                }

            }

            ibtnEdit.AlternateText = eStoreResources.ProductEditButton;
            ibtnDelete.AlternateText = eStoreResources.DeleteOrderButton;
            Utilities.AddConfirmButton(ibtnDelete, eStoreResources.ConfirmDelete);
        }

        private void LoadSettings()
        {
            if (CurrentPage.ContainsModule(moduleId))
            {
                store = StoreHelper.GetStore();
            }
        }

        void ibtnDelete_Click(object sender, ImageClickEventArgs e)
        {
            if (lbCategory.SelectedIndex > -1)
            {
                repository.DeleteeStoreCategory(int.Parse(lbCategory.SelectedValue));
                PopulateRootCategories();
            }
        }

        void ibtnEdit_Click(object sender, ImageClickEventArgs e)
        {
            if (lbCategory.SelectedIndex > -1)
            {
                WebUtils.SetupRedirect(this, "/eStore/AdminCategoryEdit.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString() + "&catid=" + lbCategory.SelectedValue);
            }
            else
            {
                WebUtils.SetupRedirect(this, "/eStore/AdminCategoryEdit.aspx?pageid=" + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString());
            }
        }

        protected virtual void SetupCss()
        {
            // older skins have this
            if (Page.Master == null) return;
            StyleSheet stylesheet = (StyleSheet)Page.Master.FindControl("StyleSheet");
            if (stylesheet == null) return;
            if (stylesheet.FindControl("styleestore") != null) return;
            Literal cssLink = new Literal
            {
                ID = "styleestore",
                Text = @"<link href='"
                       + SiteUtils.GetSkinBaseUrl()
                       + @"styleestore.css' type='text/css' rel='stylesheet' media='screen' />"
            };

            stylesheet.Controls.Add(cssLink);
        }

        private void LoadParams()
        {

            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", true, moduleId);


        }

        private void LoadPanels()
        {
            Hashtable settings = ModuleSettings.GetModuleSettings(moduleId);
            config = new eStoreConfiguration(settings);
            LoadSideContent(false, false, true, true, 0);
        }
        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        protected override void OnInit(EventArgs e)
        {
            LoadParams();
            LoadPanels();
            base.OnInit(e);

            Load += Page_Load;
            //ScriptController.RegisterAsyncPostBackControl(grdCategory);
            ibtnEdit.Click += ibtnEdit_Click;
            ibtnDelete.Click += ibtnDelete_Click;
            //grdProduct.Sorting += new GridViewSortEventHandler(grdProduct_Sorting);
            //btnAddNew.Click += new EventHandler(btnAddNew_Click);

            SuppressPageMenu();

        }

        #endregion
    }
}
